/* eslint-disable no-undef */
import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
import dotenv from 'dotenv'
import { createHtmlPlugin } from 'vite-plugin-html'
import { theme } from 'antd';

const { defaultAlgorithm, defaultSeed } = theme;

const mapToken = defaultAlgorithm(defaultSeed);
// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  // Load environment variables based on the mode
  const env = loadEnv(mode, process.cwd());
  dotenv.config({ path: `.env.${mode}` });
  const distMode = env.VITE_APP_DIST_MODE || 'para';

  // Define title and ico based on distMode
  const title = distMode === 'para' ? '并行智算云' : 'AI 智算云';
  const ico = distMode === 'para' ? '/favicon_paratera.ico' : '/favicon_blsc.ico';

  return {
    server: {
      port: 5500,
      // 如果端口被占用则尝试下一个可用端口
      strictPort: false,
    },
    plugins: [
      react({
        babel: {
          plugins: ['@babel/plugin-transform-react-jsx'], // 将 js 转换为 react 组件
        },
      }),
      createHtmlPlugin({
        minify: true,
        entry: 'src/main.jsx',
        template: 'index.html',
        inject: {
          data: {
            title
          },
          tags: [
            {
              injectTo: 'head',
              tag: 'link',
              attrs: {
                rel: 'icon',
                href: ico,
                type: 'image/x-icon'
              }
            }
          ]
        }
      })
    ],
    resolve: {
      extensions: ['.js', '.jsx', '.json', '.tsx', '.ts'],
      alias: {
        '@': path.resolve(__dirname, 'src'),
        'app': path.resolve(__dirname, 'src'),
        'lodash': 'lodash-es'
      },
    },
    css: {
      preprocessorOptions: {
        less: {
          modifyVars: mapToken,
          javascriptEnabled: true,
          additionalData: `@import "app/styles/${distMode}.less";
            @import "app/styles/default.less";`
        },
      },
    },
    esbuild: {
      loader: 'jsx',
      include: /\.jsx?$/,
    },
    optimizeDeps: {
      esbuildOptions: {
        loader: {
          '.js': 'jsx', // 将 .js 文件的 loader 设置为 jsx
        },
      },
    },
    build: {
      rollupOptions: {
        output: {
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString();
            }
          }
        }
      }
    },
    // Inject environment variables
    define: {
      'process.env': env
  }
  }
})
